package org.footito.android.ui.activity;

import org.footito.android.R;
import org.footito.android.data.Status;
import org.footito.android.data.update.UpdateService;
import org.footito.android.data.update.UpdateService.LocalBinder;
import org.footito.android.data.update.UpdateTaskListener;
import org.footito.android.tools.Log;
import org.footito.android.tools.Settings;
import org.footito.android.tools.VersionAndScreenSize;
import org.footito.android.ui.adapters.TimelineAdapter;
import org.footito.android.ui.notifications.NotificationsManager;
import org.footito.android.ui.views.TeamSelectorDialog;

import android.app.Dialog;
import android.content.ComponentName;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnGroupClickListener;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;

public class TimelineFragment extends SherlockFragment implements ServiceConnection,
		UpdateTaskListener, OnGroupClickListener {

	private static final int DIALOG_FILTER = 0;
	public static boolean isRunning = false;
	private UpdateService updateService;
	private final Handler mHandler = new Handler();
	private NotificationsManager nm;
	private ExpandableListView expandableList;
	private TimelineAdapter expandableListAdapter;
	private OnStatusClickedListener mOnStatusClickedListener;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setHasOptionsMenu(true);
		// getActionBar().setType(Type.Dashboard);

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.simple_expandablelist, null);
		expandableList = (ExpandableListView) view.findViewById(R.id.expandableListView);
		getExpandableListView().setGroupIndicator(null);
		expandableList.setOnGroupClickListener(this);
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		UpdateService.bindService(getActivity(), this);
		nm = new NotificationsManager(getActivity());
		setAdapter();
		super.onActivityCreated(savedInstanceState);
	}

	private void setAdapter() {
		expandableListAdapter = new TimelineAdapter(getActivity(), getExpandableListView());
		getExpandableListView().setAdapter(expandableListAdapter);
		expandableListAdapter.setOnStatusClickedListener(mOnStatusClickedListener);
	}

	@Override
	public void onResume() {
		super.onResume();

		TimelineFragment.isRunning = true;

		int position = 0;// Settings.getTimelinePosition(getActivity());
		getExpandableListView().setSelection(position);

		nm.removeNotifications(getActivity());

		if (VersionAndScreenSize.isLargeOrUpper(getActivity())) {
			Status topStatus = getStatus(position);
			if (topStatus != null && expandableListAdapter != null)
				mOnStatusClickedListener.onStatusClicked(topStatus);
		}
	}

	private ExpandableListView getExpandableListView() {
		return expandableList;
	}

	private ExpandableListAdapter getExpandableListAdapter() {
		return expandableListAdapter;
	}

	@Override
	public void onPause() {
		// Settings.setTimelinePosition(getActivity(),
		// getExpandableListView().getFirstVisiblePosition());
		TimelineFragment.isRunning = false;
		super.onPause();
	}

	@Override
	public void onDestroy() {
		UpdateService.unbindService(getActivity(), this);
		super.onDestroy();
	}

	@Override
	public void onServiceConnected(ComponentName name, IBinder service) {
		Log.d("Service binded");
		this.updateService = ((LocalBinder) service).getService();
		updateService.addListener(this);
	}

	@Override
	public void onServiceDisconnected(ComponentName name) {
		this.updateService = null;
	}

	@Override
	public void onComplete(int statusAdded) {
		((TimelineAdapter) getExpandableListAdapter()).loadMoreStatus();
		// getExpandableListView().invalidateViews();
		getSherlockActivity().setSupportProgressBarIndeterminateVisibility(false);
	}

	@Override
	public void onError() {
		mHandler.postDelayed(new Runnable() {
			public void run() {
				// loaderItem.setLoading(false);
				getSherlockActivity().setSupportProgressBarIndeterminateVisibility(false);
			}
		}, 2000);
	}

	@Override
	public void onProgress(ProgressEvents event, int div) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.fragment_timeline, menu);
		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.menu_top) {
			getExpandableListView().setSelection(0);
		} else if (item.getItemId() == R.id.menu_refresh) {
			getSherlockActivity().setSupportProgressBarIndeterminateVisibility(true);
			updateService.performUpdate(getActivity(), null);
		} else if (item.getItemId() == R.id.menu_bottom) {
			getExpandableListView().setSelection(getExpandableListAdapter().getGroupCount());
		} else if (item.getItemId() == R.id.menu_apropos) {
			AboutActivity.launchActivity(getActivity());
		} else if (item.getItemId() == R.id.menu_filter) {
			Dialog dialog = createDialog(DIALOG_FILTER);
			if (dialog != null)
				dialog.show();
		} else if (item.getItemId() == R.id.menu_prefs) {
			FootitoPreferenceActity.launchActivity(getActivity());
		}
		return super.onOptionsItemSelected(item);
	}

	protected Dialog createDialog(int id) {
		switch (id) {
		case DIALOG_FILTER:
			return new TeamSelectorDialog(getActivity());

		default:
			return null;
		}
	}

	public void setOnStatusClickedListener(OnStatusClickedListener listener) {
		mOnStatusClickedListener = listener;
		if (expandableListAdapter != null)
			expandableListAdapter.setOnStatusClickedListener(listener);
	}

	public interface OnStatusClickedListener {
		public void onStatusClicked(Status status);
	}

	public Status getStatus(int position) {
		if (expandableListAdapter != null)
			return (Status) expandableListAdapter.getGroup(position);
		return null;
	}

	@Override
	public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {

		for (int i = 0; i < expandableListAdapter.getGroupCount(); i++) {
			if (groupPosition != i) {
				parent.collapseGroup(i);
			} else {
				parent.expandGroup(i);
			}
		}
		return true;
	}

}
